Skip to content

Keep size balanced trees within the AVL height bound - #116

Merged
konard merged 46 commits into
mainfrom
issue-577-sbt-balance
Nov 30, 2026
Merged

konard merged 46 commits into
mainfrom
issue-577-sbt-balance

Conversation

@konard

@konard konard commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Fixes #115

Summary

All four size balanced trees now keep Chen's size balanced property after every attach and every detach: C# and C++, recursive and recursionless. Such a tree can never be taller than an AVL tree with the same number of nodes. Balancing still uses only the subtree sizes; no field is added to the nodes.

  • The recursive trees run Chen's original Maintain on every attach and every detach.
  • The recursionless trees run the same algorithm without recursion. They make the same rotations in the same order and build the same trees, which the tests check. An attach also uses the direction it took at each node, so it needs fewer size reads than the recursive tree.
  • Inspection costs the library nothing. Rotation and size-read counting lives in the test trees, which inherit from the library trees (see below).
  • Coverage is 100% of lines in C# and C++. CI fails the build below that.
  • Tests run on every pull request and on main. Benchmarks run on request, and CI follows the current linksplatform and hive-mind practices.

Found in linksplatform/Data.Doublets#577: the source index of the united links store had grown to 1,992 levels for 4,097 links, where the bound is 16.

What a size balanced tree must guarantee

Chen (2007): for every node t

size(t.left)  >= size(t.right.left)  and  size(t.left)  >= size(t.right.right)
size(t.right) >= size(t.left.left)   and  size(t.right) >= size(t.left.right)

The smallest tree of height h that keeps this property has m(h) = m(h-1) + m(h-2) + 1 nodes, exactly like the smallest AVL tree:

height 1 2 3 4 5 6 8 10 13 16 18
min nodes 1 2 4 7 12 20 54 143 609 2583 6764

So 7 nodes may need 4 levels but never 5, 4,097 nodes never more than 16 levels, 8,192 nodes never more than 18. The new tests check exactly this bound (GetMaximumBalancedHeight) and the property itself after every operation.

Chen's Maintain(t, leftMayBeHeavy) restores the property after a single attach or detach. After each rotation it repairs, in this order, the left child, the right child, and then t in both directions (Maintain(left, false); Maintain(right, true); Maintain(t, true); Maintain(t, false)). Each call is amortised O(1), so attach and detach stay O(log n).

What was wrong

Variant Defect
C# SizeBalancedTreeMethods attachCount/maintainThreashold (added for #103) skips Maintain on every second attach. DetachCore never runs Maintain.
C# RecursionlessSizeBalancedTreeMethods A one-pass rotation heuristic, not Chen's algorithm: it checks one level per node on the way down and never repairs the subtrees changed by its rotations. Same on detach.
C++ SizeBalancedTreeMethods Attach is Chen's algorithm (with the repair order Left then Right instead of Chen's). DetachCore never runs Maintain.
C++ RecursionlessSizeBalancedTreeMethods The same heuristic as in C#.

Example 1: the skipped Maintain (C# recursive tree)

In Data.Doublets every new link is attached to two indexes. When many links share one source, their keys are adjacent ("hot") and are attached alternately with unrelated ("cold") keys. With the threshold, Maintain runs only on every second attach, so every hot attach lands on the turn without Maintain. Keys 1, 5, 2, 6, 3, 7, 4, 8 (hot 1..4, cold 5..8):

0.7.x (threshold)        Chen (this PR)
5                        5
  1                        2
    2                        1
      3                      3
        4                      4
  7                        7
    6                        6
    8                        8
height 5 (bound 4)       height 4

(Drawn by experiments/sbt-heal/sbt_model.py, a model of the C# code; the C# experiment HotColdHeights.cs measures the same heights on the real classes.)

With 2,048 hot and 2,048 cold keys the old C# tree has height 2,049 — the hot half is a plain linked list — while Chen's tree has height 13 (bound 16). This is the shape Data.Doublets#577 found in real data.

Example 2: detach without Maintain (C++ recursive tree)

Attach 1..4096 (a perfectly fine tree) and then detach every node except those on the path from the root to key 1. Without Maintain on detach nothing shortens that path: the old tree is left with 12 nodes and height 12 (bound 5). With this PR it has height 4, the same as the AVL tree.

Example 3: the one-pass heuristic (recursionless trees)

The same hot/cold workload gives the old C# recursionless tree height 17 for 4,096 nodes (bound 16) and the old C++ recursionless tree height 19 for 8,192 nodes (bound 18). Detaching 1..4032 of 1..4096 leaves the old C++ recursionless tree with 64 nodes and height 8, at the bound, where the AVL tree has 7. With this PR the recursionless trees build exactly the same shapes as the recursive ones (14 and 7).

Measured with the experiment programs in linksplatform/Data.Doublets#592 (experiments/sbt-heal):

workload bound old recursive old recursionless new (both) AVL
C#: hot/cold, 8 nodes 4 5 4 4 —
C#: hot/cold, 4,096 nodes 16 2,049 17 13 —
C++: keep the path to key 1 5 for 12 nodes 12 (12 nodes) 5 (18 nodes) 4 (12 nodes) 4 (12 nodes)
C++: hot/cold, 8,192 nodes 18 14 19 14 14
C++: detach 4,032 of 4,096 8 for 64 nodes 7 8 7 7

The fix

Shared base, SizedBinaryTreeMethodsBase (C# and C++)

  • GetMaximumBalancedHeight(size) returns the height bound from the table above.
  • RebuildComplete(root) is Day–Stout–Warren: it rotates the subtree into a vine and folds the vine into a complete tree. It takes O(n) time and O(1) memory, and the rotations keep the sizes correct. A complete tree is size balanced.

Recursive tree, SizeBalancedTreeMethods (C# and C++)

Recursionless tree, RecursionlessSizeBalancedTreeMethods (C# and C++)

It is the same algorithm with an explicit path of steps (parent and side, so a step stays valid when a rotation replaces the node) and a small Maintain stack.

MaintainAttachPath uses the direction an attach took. Before the attach the tree was balanced, and the attach enlarged only the grandchild on the path. So until a rotation changes the children, Maintain can only rotate because of that grandchild, and the tree compares only its size.

After a rotation, MaintainRotated runs the four Maintain calls of the paper from the stack, in the paper's order. The result:

  • the same rotations in the same order as the recursive tree (RecursiveAndRecursionlessTreesMakeTheSameRotations);
  • fewer size reads (RecursionlessAttachReadsFewerSizes);
  • no recursion: the path and the stack are reused arrays (C#) or vectors (C++) of the instance.

Trees stored by older versions

Trees in memory-mapped files (Data.Doublets) may already be degenerate, and Maintain only repairs the path of the current operation. So both trees count the levels an attach or detach passes. When that count exceeds GetMaximumBalancedHeight(size), the tree cannot have been built by this algorithm, and it is rebuilt once with RebuildComplete. A tree built by this code never triggers the rebuild, because the bound is a theorem.

Paying only for what you use

Requested in #116 (comment).

  • The library has no counters, logs or hooks for inspection.
  • The test trees are inheritors of the library trees. They count size reads in GetSize, and rotations in SetLeft and SetRight, accessors every tree implements anyway. A rotation is the only change of links that puts a node below its former child.
  • C#: LeftRotate and RightRotate stay non-virtual, as on main. RotationsAreNotVirtual guards that.
  • C++: the test trees shadow the rotations through CRTP, which resolves them at compile time. static_assert(!std::is_polymorphic_v<...>) keeps the library trees free of vtables.
  • Validation mode (ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION) is compile-time only. Its exceptions are kept, and C# can be built with it through -p:TreeValidation=true.

Tests

C# C++
tests 85 xUnit tests 54 Google Test tests
line coverage of the library 825 / 825 (check-csharp-coverage.mjs) 840 / 840 (gcovr --fail-under-line 100)
self-validating trees -p:TreeValidation=true job linux-gcc-sanitizers-validation job (ASan + UBSan, Debug)

The tests cover:

  • Balance after every operation: Chen's property and the AVL height bound, after every attach and detach. The workloads are ascending, descending, random, interleaved hot/cold, alternating ends, random churn, and every order of up to 8 nodes. A tree that is not size balanced fails at once.
  • Minimum rotations:
    • An attach rotates if and only if a plain insertion would break the property.
    • Level-order attach of a complete tree makes no rotations.
    • Rotations per attach are constant on average.
  • Identical trees: the recursive and recursionless trees make the same rotations and build the same shapes.
  • Edge cases:
    • detach of missing nodes and of nodes with shared keys;
    • rebuilding degenerate trees built by other code;
    • size validation and repair;
    • neighbour lookups;
    • AVL rotations with balances, sizes and threads;
    • AVL attach or detach failures that undo their size changes;
    • doubly linked lists, against a model.

Before this PR, 16 of 24 C# balance tests and 10 of 20 C++ balance tests failed.

Benchmarks, memory and limits

Requested in #116 (comment). Every tree and every list is benchmarked in C# (BenchmarkDotNet) and C++ (Google Benchmark), on the same storages as the tests:

  • TreeBenchmarks: attach and detach of N = 1,000 and 100,000 nodes, in ascending, descending and random order.
  • TreeSearchBenchmarks: search of every node.
  • ListBenchmarks: attach and detach in all four doubly linked lists.
  • StorageBenchmarks: the memory of the storage of N nodes.

Each table shows the mean time, the ratio to the first structure, and the allocated bytes. render-benchmarks.mjs normalizes both outputs into benchmarks/results.json and renders it into README.md between markers. --check fails CI when the README and the JSON differ. README.md is the readme of both NuGet packages: PackageReadmeFile for C# and <readme> in the nuspec for C++. Package validation checks that the README is in each package.

README.md now also has:

  • Choosing a structure, from the measured results.
  • Memory: bytes per node, and the memory besides the nodes.
  • Limits: max nodes per element type, max height, uniqueness, exceptions, thread-safety. The tests fill byte trees with all 255 nodes and bound the AVL path.

Measured results (Benchmarks run 46286800162, committed into README.md):

  • AVL tree: attach/detach take 0.4–0.75× the time of the recursive SBT, but search takes 1.06–2.1× as long. It uses 16 B per uint node, the SBT 12 B.
  • Recursive SBT vs recursionless SBT: the recursionless tree takes 1.1–1.46× the time. The explicit path costs more than the shallow O(log n) recursion it replaces. Both build identical trees; the recursionless tree is for limited stacks and degenerate data from older versions.
  • Lists vs trees: lists are 24–145× faster than trees of 1,000 elements, and use 8 B per node. The Open lists take about 0.8× the time of the Circular ones.
  • Allocations: attach, detach and search allocate nothing on the heap. Allocation-counting tests prove it in both languages. The 1–147 B that BenchmarkDotNet shows are runtime noise of MemoryDiagnoser; the README explains this.

The benchmarks run on request (Actions → Benchmarks → Run workflow). With commit-results the workflow commits new results to README.md and benchmarks/results.json.

Architecture

Applied https://github.com/link-foundation/code-architecture-principles across the codebase:

  • Inspection is a decorator in the tests.
    • The test trees are split into plain trees and Inspectable* inheritors. The plain trees are what the benchmarks measure.
    • The C++ InspectableTree is a CRTP mixin.
    • Inheritors get the node accessors, the rotations, RebuildComplete and GetMaximumBalancedHeight. The Maintain steps and the reused path buffers stay private in C# and C++. Rotations stay non-virtual.
  • No hidden allocations.
    • The AVL tree reuses its path buffer in both languages.
    • The recursionless tree reuses its path and Maintain stack.
    • The C++ test allocation counter replaces every operator new/delete form. This includes the nothrow forms GoogleTest uses, which the AddressSanitizer job needs to see matching new and delete.
  • Explicit names and state.
    • sb is renamed to stringBuilder.
    • RotationDetector is a class, so its state is never copied.
    • The benchmark helpers return roots instead of taking them by ref.
    • The public API keeps Attach(ref root, node) and Detach(ref root, node): the inheritor owns the storage of the root, and the trees update it in place. GlobalSuppressions.cs documents this for SonarC# S3874. experiments/sonar runs SonarC# locally, as Codacy does.
  • One source of truth for results. Benchmark results live in benchmarks/results.json. The README is generated from it and checked against it.

CI/CD

Workflow Runs on Does
csharp.yml pull requests, main build with -warnaserror, tests, 100% coverage gate, TreeValidation tests, NuGet package validation, docfx API site and PDF of the code. On main also: release preflight, trusted-publishing push, GitHub release, docs.
cpp-test.yml pull requests, main gcc, clang, AppleClang, MSVC; a gcc Debug job with sanitizers and validation; 100% gcovr gate; NuGet pack plus a consumer build
deploy-cpp.yml main (nuspec version bump) trusted publishing of the template library
benchmarks.yml manual (workflow_dispatch) C# and C++ benchmarks of all trees and lists; results in the summary and artifacts, and with commit-results committed into README.md
codeql.yml pull requests, main, weekly CodeQL for actions, C/C++ and C#, plus dependency review
workflows.yml pull requests, main actionlint, zizmor, workflow policy tests
secrets.yml, readme-badges.yml, AutoMerge.yml pull requests, main secretlint; badge check plus render-benchmarks.mjs readme --check; Dependabot auto-merge

The practices follow csharp-ai-driven-development-pipeline-template, hive-mind BEST-PRACTICES.md and CI-CD-BEST-PRACTICES.md, and linksplatform/Interfaces:

  • Actions are pinned (third-party ones by SHA), persist-credentials: false, least-privilege permissions, timeout-minutes on every job.
  • concurrency never cancels runs on main.
  • An aggregate pipeline status job gates the release.
  • tj-actions/changed-files, which was compromised, is replaced by git diff. This closes the two open Dependabot alerts.
  • Node tests cover every release and CI script (node --test .github/scripts/*.test.mjs).

Trusted publishing comes first. NuGet/login (OIDC) needs nuget.org policies for csharp.yml and deploy-cpp.yml and the repository variable NUGET_USER. Without them the workflows fall back to the NUGET_TOKEN API key, and a preflight explains what is missing. The steps are in the README, under "Releasing".

Not ported

  • Bilingual XML docs check: many existing XML docs have empty Russian paragraphs.
  • clang-format check: the existing C++ sources do not follow one format.
  • The rust submodule: it has no size balanced tree.

Each of these would mean reformatting or translating the whole existing codebase, outside this issue.

CodeQL: .github/codeql/codeql-config.yml excludes only cpp/include-non-header and cpp/unused-static-variable:

  • The first reports the unity builds of the C++ tests and benchmarks, the linksplatform layout.
  • The second misreads a benchmark function template as a variable, because buildless extraction lacks the fetched Google Benchmark headers.

Codacy: the pull request adds no new issue (SonarC#, cppcheck, markdownlint, pydocstyle). .markdownlint.json sets the 80-column line length that the README and the generated benchmark section follow.

Documentation: DocFX builds the README as the home page with --warningsAsErrors. validate-csharp-docs.sh checks on every pull request that the namespace and tree pages and the API documentation PDF exist, and that the README links them.

Release

  • C#: VersionPrefix 0.8.0.
  • C++: nuspec 0.4.0, with release notes.
  • Merging publishes both through the workflows above, once a maintainer has set up trusted publishing (or NUGET_TOKEN).
  • Data.Doublets#592 keeps a temporary copy of the fixed tree until 0.8.0 is published.

Restore Chen's size balanced tree algorithm: Maintain after every attach
(removing the skip-every-second-attach threshold) and after every detach.
The recursionless variant is the same algorithm with explicit stacks, so
both build trees of identical shape. Trees built by older versions are
rebuilt once with Day-Stout-Warren when an operation passes more nodes
than any size balanced tree of that size can have.

Refs #115, linksplatform/Data.Doublets#577
Run Maintain after every detach in SizeBalancedTreeMethods and replace
the RecursionlessSizeBalancedTreeMethods heuristic with Chen's algorithm
using explicit stacks, matching the C# implementation. Add balance tests
that check the height bound and the size balanced property.

Refs #115, linksplatform/Data.Doublets#577
konard added a commit to linksplatform/Data.Doublets that referenced this pull request Nov 29, 2026
Replace the weight-balanced repair with a copy of the fixed
RecursionlessSizeBalancedTreeMethods from linksplatform/Collections.Methods#116:
Maintain runs on every attach and detach, and an index whose path is longer
than the AVL height bound (written by an older version) is rebuilt once.
The tests now check Chen's size balanced property and the AVL height bound
for all index tree types.
Brace single-statement loops and conditions in TreeBalanceTests, fold the
vine with a while loop, and return the new root from RebuildComplete
instead of taking it by reference.
@konard

konard commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Double check we have original Size Balanced Tree maintain in a recursive mode for recursive tree implementation, double check we have 100% tests coverage, so nothing breaks what was working, and we also check for perfect balance and minimum rotations.

RecursionlessSizeBalancedTreeMethods idea was to implement similar algorithm, but with no actual recursion so it should be even cheaper on method calls and so on. So we should have fully recursive and fully recursion less implementation and all of them must be perfectly correct.

When we use recursion less implementation we should use knowledge on where we actually going while putting a node in the tree, so we can keep tree balanced/maintained probably with less computational expenses. Double check everything, make sure everything works perfectly in unit tests - they should say it impossible to get way to unbalanced tree, and also in benchmarks, we should make CI/CD in such a way, that we have manual benchmarks execution, yet we also have CI/CD executing unit tests on any pull request and default branch.

We also must use all the best fresh best practices from https://github.com/link-foundation/csharp-ai-driven-development-pipeline-template, and prepare our repository for trusted publishing will be the first priority, and all other obsolete methods as a fallback.

https://github.com/link-assistant/hive-mind/blob/main/docs/BEST-PRACTICES.md - also use all these.

So as this is a critical piece of our infrastructure all our algorithms must be perfectly correct and be as performant as possible, yet as simple as possible.

We need to ensure all changes are correct, consistent, validated, tested, documented, logged and fully meet each and all discussed requirements in deepest and widest possible sense (check issue description and all comments in issue and in pull request, make sure each and every requirement listed before actually checking if they were addressed). Nothing should be defered or delayed. The scope is the entire repository, every change in one place should also be applied in all places in the codebase and docs. Ensure all CI/CD checks pass.

Please plan and execute everything in this single pull request, you have unlimited time and context, as context auto-compacts and you can continue indefinitely, until each and every requirement fully addressed, and everything is totally done.

@konard
konard marked this pull request as draft November 29, 2026 09:21
@konard

konard commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

🤖 AI Work Session Started

Started at 2026-11-29T09:21:56.795Z. Please wait for it to finish before giving feedback.

Runtime: solve v2.50.0 · tool claude · model opus · task image konard/hive-mind-dind:2.50.0@sha256:39bda1084d8f7e24e6f1f758c32f40113f68d385759aa862c36b72e9b7570bb6

The recursionless size balanced tree remembers which way the attach went at
every node, so on the way back up it compares only the grandchild that grew
until a rotation changes the children. This gives the same rotations as Chen's
Maintain with half of the size comparisons. Rotations are virtual so tests can
count them, and the debug validation code compiles and checks the right sizes.
Mirrors the C# change: direction aware attach maintenance, Maintain steps on an
explicit stack, size checks that accept empty children, and debug validation
that compiles (ValidateSizes, FixSizes and ValidateSize are now available).
Every Maintain call in the recursive tree targets a node on the path of
the operation or a child that a rotation has just moved up, so the
subtree is never empty. The recursionless maintenance stack now starts
with 8 steps and grows on demand.
A duplicate attach or a detach of a missing node threw after the sizes on
the search path were already changed, which left the tree invalid. Both
the C# and the C++ AVL trees now restore the sizes before throwing.
- Rotations happen exactly when the size balanced properties require them,
  and the recursive and the recursionless trees rotate identically.
- Every order of up to eight nodes keeps the properties.
- Failed operations, size validation, printing, neighbours, rebuild and the
  maximum balanced height are covered for every tree.
- Doubly linked lists are checked against a reference model.
Port the rotation, edge case and doubly linked list tests to C++, instrument
the test trees to count rotations and size reads, and report the missing node
in the detach error message as the C# trees do.
The C# benchmarks use BenchmarkDotNet, the C++ benchmarks use google
benchmark. Both attach and detach 1000 and 100000 nodes in ascending,
descending and random order.

CMake now registers the tests with CTest, requires GTest and benchmark
only for the targets that use them, and fetches the Platform.Interfaces
headers (cpp_0.3.41) when conan does not provide them.
…ge provides them

Add options for sanitizers, gcov coverage and tree self-validation so CI
builds every configuration from the same CMakeLists.txt.
…ling a consumer

The nuspec now depends on Platform.Interfaces.TemplateLibrary 0.3.41, whose
Polymorph.h the headers include. The icon and MSBuild targets come from the
last published package (0.3.0).
@konard

konard commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

I think inspectable tree must be done as inheritor or decorator, so the default tree implementation must not pay (memory or computation) for inspection. So we can support both features, but when inspection is not needed (we are in production code, not in development/debug or testing), we can just not pay for it.

So we should allow to pay only for what we get, and if something is optional we don't force all users to pay for it.

…equest

Detach in ENABLE_TREE_AUTO_DEBUG_AND_VALIDATION mode no longer checks for
a missing node itself, so it throws the same exception as without
validation (C++ and C#). dotnet test -p:TreeValidation=true defines the
symbol for C#.

The library builds with -warnaserror (nullable fixes, Source Link 8.0.0)
and the package carries the README, the icon and embedded symbols.
…overage

cpp/build-and-test.sh builds the tests and runs them through CTest.
cpp-test.yml runs it on pull requests and main for GCC, Clang, AppleClang
and MSVC, once with AddressSanitizer, UBSan and self-validating trees, and
requires 100% line coverage of the headers with gcovr. deploy-cpp.yml
publishes only the tested package, with NuGet trusted publishing first and
NUGET_TOKEN as a fallback, after a release preflight.
csharp.yml now runs on pull requests and main without the shared
linksplatform/Workflows jobs: it tests and packs the library, requires
100% line coverage (check-csharp-coverage.mjs), reruns the tests with
-p:TreeValidation=true, builds the docfx site and PDF, and publishes to
nuget.org with trusted publishing first and NUGET_TOKEN as a fallback.
pipelineStatus fails if any required job failed or was skipped.
Benchmarks are noisy on shared runners, so benchmarks.yml runs only from
workflow_dispatch and stores the results in the run summary and artifacts.
The test workflows keep the benchmarks compiling.
workflows.yml runs actionlint, zizmor and the workflow policy tests;
secrets.yml scans for committed secrets; codeql.yml analyzes Actions, C++
and C# and reviews dependency changes; readme-badges.yml checks that the
badges point at existing workflows. Dependabot also updates the actions,
with a cooldown, and AutoMerge.yml enables auto-merge with gh instead of
the removed @dependabot merge comments. The README documents the balance
guarantees, tests, benchmarks and the trusted publishing setup.
@github-advanced-security

Copy link
Copy Markdown

You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool.

What Enabling Code Scanning Means:

  • The 'Security' tab will display more code scanning analysis results (e.g., for the default branch).
  • Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results.
  • You will be able to see the analysis results for the pull request's branch on this overview once the scans have completed and the checks have passed.

For more information about GitHub Code Scanning, check out the documentation.

LeftRotate and RightRotate are non-virtual again, as on main. The test trees,
which inherit from the library trees, now count rotations in the SetLeft and
SetRight accessors they implement anyway: a rotation is the only change of
links that makes a node the child of its former child. A cross-check run
(experiments/detect_rotations_in_setters.py --cross-check) confirmed that the
setters detect exactly the rotations the overrides saw.

A C# test fails if a rotation becomes virtual, and C++ static_asserts keep
the library trees free of virtual functions; the C++ test trees shadow the
rotations through CRTP, which resolves them at compile time.
The csharp test job and the C++ pack job failed with "Permission denied"
(exit code 126) because six scripts were committed without the executable
bit. A workflow policy test now requires it for every tracked shell script.
install-local-conan-dependencies.sh gets a shebang and strict mode.
cpp/include-non-header flags the unity builds of the C++ tests and
benchmarks, the linksplatform layout. cpp/unused-static-variable misreads a
benchmark function template as a variable, because the buildless extraction
does not have the fetched Google Benchmark headers.
@konard

konard commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

I think inspectable tree must be done as inheritor or decorator, so the default tree implementation must not pay (memory or computation) for inspection. So we can support both features, but when inspection is not needed (we are in production code, not in development/debug or testing), we can just not pay for it.

So we should allow to pay only for what we get, and if something is optional we don't force all users to pay for it.

Double check #116 (comment) is fully addressed, as well as #115

We need to have perfect possible solution, extensible, configurable and so on.

Use all the best https://github.com/link-foundation/code-architecture-principles, and apply it to entire codebase, for all similar algorithms like trees we benchmark relative+absolute performance and also memory usage, and limitations (like maximum possible supported items and so on).

We also need to make sure results of benchmarks are clearly visible in our README.md where relevant and applicable, also in all packages we release, so user can see benefits and can compare implementations before selecting which best fits his needs.

Double check for maximum perfection of every detail in this repository.

We need to ensure all changes are correct, consistent, validated, tested, documented, logged and fully meet each and all discussed requirements in deepest and widest possible sense (check issue description and all comments in issue and in pull request, make sure each and every requirement listed before actually checking if they were addressed). Nothing should be defered or delayed. The scope is the entire repository, every change in one place should also be applied in all places in the codebase and docs. Ensure all CI/CD checks pass.

Please plan and execute everything in this single pull request, you have unlimited time and context, as context auto-compacts and you can continue indefinitely, until each and every requirement fully addressed, and everything is totally done.

@konard
konard marked this pull request as draft November 29, 2026 16:04
@konard

konard commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

🤖 AI Work Session Started

Started at 2026-11-29T16:04:41.406Z. Please wait for it to finish before giving feedback.

Runtime: solve v2.50.0 · tool claude · model opus · task image konard/hive-mind-dind:2.50.0@sha256:39bda1084d8f7e24e6f1f758c32f40113f68d385759aa862c36b72e9b7570bb6

…s path buffer

The tree methods keep their helpers protected instead of private, so an
inheritor can observe them without the plain tree paying anything for it.
The C# AVL tree allocated a new path array on every attach and detach; it
now reuses one buffer per tree, which TreeAllocationTests proves by
measuring zero allocated bytes for every tree.
SizeBalancedTree, RecursionlessSizeBalancedTree and
SizedAndThreadedAVLBalancedTree of the tests are now plain storage, as a
user of the library would write them. Rotation and size read counting,
the rotation log and the inspection helpers live only in the
Inspectable* inheritors (C#) and in the InspectableTree CRTP decorator
(C++), which the balance, rotation and edge case tests use. Static
asserts check that the plain C++ tree is exactly its nodes plus root and
count, so nothing is paid for inspection.
…locations

The C++ benchmarks are registered under the same group, structure and
parameter names as their C# counterparts, so one renderer can compare
them, and report the bytes allocated per iteration through a counting
global operator new. The same counter backs new TreeAllocationTests,
which check that the plain trees allocate nothing per attach and detach
once warmed up, as the C# TreeAllocationTests do.
…nd bound the AVL path

Byte trees of all three kinds now hold the nodes 1..255 in both languages.
The C++ AVL tree keeps its path in a std::array and writes it with at(), so a
tree deeper than any AVL tree, which only other code can link, throws
std::out_of_range instead of writing past the stack array (GCC warned about
that for byte trees). C# already threw IndexOutOfRangeException; tests now
prove both. The dead USEARRAYPOOL branches are gone.
The Benchmarks workflow normalizes the BenchmarkDotNet and Google Benchmark
JSON into benchmarks/results.json and renders it into README between markers,
shows the tables in the run summary and, with commit-results, commits both.
The README check workflow tests the renderer and fails when README does not
show the committed results. README now compares the structures, describes
their memory per node and besides the nodes, and lists their limits.
The C++ package now carries README.md like the C# package, and both package
checks fail when README.md lacks the benchmark section. Both descriptions say
what README.md compares.
…nd delete

GoogleTest sorts the tests with std::stable_sort, which allocates its
buffer with the nothrow operator new and frees it with operator delete.
The test executable replaced operator delete with free but left the
nothrow operator new to the standard library, so the sanitizer job
aborted with alloc-dealloc-mismatch before the first test.
…y them

The Benchmarks workflow run 46286800162 measured C# and C++ on the same
runner. AVL attaches and detaches in 0.4-0.75 of the size balanced tree's
time but searches 1.06-2.1 times as long; the recursive size balanced
tree is faster than the recursionless one. The guide now follows these
numbers instead of preferring the recursionless tree.
Reverts the temporary push trigger of 47bd4ee now that README holds the
measured results.
Addresses the CodeQL note about the implicit filter without adding LINQ
delegates to the measured loop.
Self-documented names with full words, as code-architecture-principles
asks; the parameter is only renamed, so positional callers are unaffected.
The renderer wraps the generated benchmark prose, uses level 3 headings under
the section and * bullets, and .markdownlint.json states the line length the
README keeps, so Codacy's markdownlint reports nothing.
A mutable struct kept in a readonly field would be copied on every call; the
inspectable trees now keep one detector instance.
The benchmark helpers no longer take the root by reference. The library keeps
ref roots on purpose: the inheritor owns the storage of the root and the trees
update it in place, so SonarC# S3874 is suppressed with that justification.
Inheritors implement the node accessors and may use the rotations,
RebuildComplete and GetMaximumBalancedHeight; the Maintain steps and the
reused path buffers are implementation details that no inheritor needs, so
they are private again in C# and C++. This also removes the 13 SonarC# S3874
issues Codacy reported on the new ref-taking helpers.
dotnet build experiments/sonar reports S3874 and the other SonarC# rules
locally, so Codacy findings can be reproduced before pushing.
@konard
konard marked this pull request as ready for review November 29, 2026 20:38
@konard

konard commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Working session summary

PR #116 is updated and marked ready for review: #116. All 27 checks pass on the final commit 19164d8, and Codacy reports 0 new issues, so its quality gate passes. The 4 skipped checks are jobs that only run on main, such as release and publishing.

Codacy fixes (59 issues → 0):

  • markdownlint: the README and its generated benchmark section now wrap at 80 columns and use consistent headings, bullets and table rows. A new .markdownlint.json sets those rules, and the README check in CI still confirms the README matches the benchmark results.
  • SonarC# S3874 (13 issues): Codacy ignores in-code suppressions, so I made the balancing helpers and their reused buffers private in both C# and C++. Nothing outside the tree classes used them. Inheritors still get the node accessors, the rotations, RebuildComplete and GetMaximumBalancedHeight. The public Attach(ref root, node) and Detach(ref root, node) keep ref on purpose, because the caller owns where the root is stored.
  • Smaller code fixes:
    • The benchmark helpers return the root instead of taking it by ref.
    • RotationDetector is now a class, so its state isn't silently copied.
    • sb is renamed to stringBuilder.
  • Reproducing Sonar locally: experiments/sonar runs SonarC# on the library the way Codacy does. Locally it showed exactly Codacy's 13 issues before the change, and only the 6 on the unchanged public API afterwards.

Verification:

  • C#: 85 tests pass and the build has no warnings with warnings treated as errors. Line coverage is 100% (825 of 825).
  • C++: 54 tests pass, including the AddressSanitizer job that failed earlier. Line coverage is 100% (840 of 840).
  • The 139 tests for the CI and release scripts pass.

The PR description still says "Fixes #115". It now has the current test and coverage numbers, the measured benchmark results, the new README sections on memory and limits, the README shipped in both NuGet packages, and a section on the code-architecture changes. The branch is clean, pushed and up to date with main.

One thing left out of scope: the description lists three items not ported from the template repo — the bilingual XML docs check, a clang-format check, and the rust submodule. Each would mean reformatting or translating existing code outside this issue. Since the review comment asked that nothing be deferred, you may want to decide whether that's acceptable.


This summary was automatically extracted from the AI working session output.

@konard

konard commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

🤖 Solution Draft Log

This log file contains the complete execution trace of the AI solution draft process.

💰 Cost estimation:

  • Public pricing estimate: $15.736449
  • Calculated by Anthropic: $15.769257
  • Difference: $0.032808 (+0.21%)

📊 Context and tokens usage:

Claude Opus 5.5: (7 sub-sessions)

  1. 116.1K / 1M (12%) input tokens, 19.8K / 128K (15%) output tokens
  2. 114.8K / 1M (11%) input tokens, 36.8K / 128K (29%) output tokens
  3. 113.6K / 1M (11%) input tokens, 47.5K / 128K (37%) output tokens
  4. 115.7K / 1M (12%) input tokens, 32.5K / 128K (25%) output tokens
  5. 106.9K / 1M (11%) input tokens, 23.1K / 128K (18%) output tokens
  6. 115.5K / 1M (12%) input tokens, 32.8K / 128K (26%) output tokens
  7. 92.9K / 1M (9%) input tokens, 26.1K / 128K (20%) output tokens

Total: (121.9K new + 676.1K cache writes + 23.2M cache reads) input tokens, 262.1K output tokens, $15.736449 cost

🤖 Models used:

  • Tool: Anthropic Claude Code
  • Requested: opus (claude-opus-5-5)
  • Thinking level: high (~23999 tokens)
  • Model: Claude Opus 5.5 (claude-opus-5-5)

📎 Log file uploaded as Gist (12621KB)


This AI session has ended. Monitoring of this pull request continues. Feel free to review and add feedback while checks are running.

@konard

konard commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

✅ Ready to merge

This pull request is now ready to be merged:

  • All CI checks have passed
  • No merge conflicts
  • No uncommitted changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Size balanced trees lose the size balanced property and grow far beyond the AVL height bound

2 participants